/**
 * 客户邀请管理页面JavaScript
 * 基于Apple Design System的交互设计
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let invitationData = [];
let filteredData = [];
let selectedCustomers = [];
let currentFilter = 'all';
let filterCriteria = {};

// DOM 元素
const batchInviteBtn = document.getElementById('batch-invite-btn');
const applyFilterBtn = document.getElementById('apply-filter-btn');
const resetFilterBtn = document.getElementById('reset-filter-btn');
const viewBtns = document.querySelectorAll('.view-btn');
const invitationTableBody = document.getElementById('invitation-table-body');
const batchActionsBar = document.getElementById('batch-actions-bar');
const selectedCountSpan = document.getElementById('selected-count');
const selectAllCheckbox = document.getElementById('select-all');
const invitationModal = document.getElementById('invitation-modal');
const invitationDetailModal = document.getElementById('invitation-detail-modal');

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    initializeRangeSliders();
    initializeTagSelector();
    loadInvitationData();
    updateInvitationDisplay();
    updateStats();
});

// 初始化事件监听器
function initializeEventListeners() {
    // 筛选操作
    applyFilterBtn.addEventListener('click', applyFilters);
    resetFilterBtn.addEventListener('click', resetFilters);
    
    // 视图切换
    viewBtns.forEach(btn => {
        btn.addEventListener('click', () => switchView(btn.dataset.view));
    });
    
    // 批量操作
    batchInviteBtn.addEventListener('click', openInvitationModal);
    selectAllCheckbox.addEventListener('change', handleSelectAll);
    
    // 模态框
    document.addEventListener('click', handleModalClick);
    document.addEventListener('keydown', handleKeyDown);
    
    // 表单变化
    initializeFormListeners();
}

// 初始化范围滑块
function initializeRangeSliders() {
    const ageMinSlider = document.getElementById('age-min');
    const ageMaxSlider = document.getElementById('age-max');
    const ageRangeDisplay = document.getElementById('age-range-display');
    
    function updateAgeRange() {
        const min = parseInt(ageMinSlider.value);
        const max = parseInt(ageMaxSlider.value);
        
        // 确保最小值不大于最大值
        if (min > max) {
            ageMinSlider.value = max;
            ageMaxSlider.value = min;
        }
        
        ageRangeDisplay.textContent = `${ageMinSlider.value}-${ageMaxSlider.value}岁`;
    }
    
    ageMinSlider.addEventListener('input', updateAgeRange);
    ageMaxSlider.addEventListener('input', updateAgeRange);
    
    // 初始化显示
    updateAgeRange();
}

// 初始化标签选择器
function initializeTagSelector() {
    const tagItems = document.querySelectorAll('.tag-item');
    
    tagItems.forEach(item => {
        item.addEventListener('click', function() {
            this.classList.toggle('active');
            updateFilterResult();
        });
    });
}

// 初始化表单监听器
function initializeFormListeners() {
    const customerCheckboxes = document.querySelectorAll('.customer-checkbox');
    
    customerCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', handleCustomerSelection);
    });
}

// 加载邀请数据
function loadInvitationData() {
    // 模拟邀请数据
    invitationData = [
        {
            id: 1,
            customerId: 'CRM2025000001',
            customerName: '张大爷',
            customerPhone: '138****8001',
            customerAvatar: '张',
            customerStatus: '有效客户',
            customerTags: ['VIP客户', '身体健康'],
            invitationMethods: ['电话邀请', '微信确认'],
            firstInviteTime: '2025-07-18 09:30',
            lastInviteTime: '2025-07-19 15:20',
            customerFeedback: '很感兴趣，会准时参加',
            invitationStatus: 'confirmed',
            followUpTime: '2025-07-24 10:00',
            followUpMethod: '活动提醒',
            age: 68,
            region: '本市',
            budget: '5000-8000'
        },
        {
            id: 2,
            customerId: 'CRM2025000002',
            customerName: '李大妈',
            customerPhone: '139****8002',
            customerAvatar: '李',
            customerStatus: '潜在客户',
            customerTags: ['优质客户', '需要关怀'],
            invitationMethods: ['电话邀请'],
            firstInviteTime: '2025-07-19 14:15',
            lastInviteTime: '2025-07-19 14:15',
            customerFeedback: '',
            invitationStatus: 'pending',
            followUpTime: '2025-07-21 09:00',
            followUpMethod: '电话跟进',
            age: 65,
            region: '本市',
            budget: '3000-5000'
        },
        {
            id: 3,
            customerId: 'CRM2025000003',
            customerName: '王先生',
            customerPhone: '137****8003',
            customerAvatar: '王',
            customerStatus: '有效客户',
            customerTags: ['普通客户'],
            invitationMethods: ['短信邀请'],
            firstInviteTime: '2025-07-18 16:45',
            lastInviteTime: '2025-07-18 16:45',
            customerFeedback: '最近身体不太好，不参加了',
            invitationStatus: 'rejected',
            followUpTime: '-',
            followUpMethod: '无需跟进',
            age: 72,
            region: '邻近城市',
            budget: '8000-12000'
        }
        // 更多模拟数据...
    ];
    
    filteredData = [...invitationData];
}

// 更新邀请显示
function updateInvitationDisplay() {
    renderInvitationTable();
    updateResultCount();
}

// 渲染邀请表格
function renderInvitationTable() {
    invitationTableBody.innerHTML = '';
    
    const dataToShow = getFilteredData();
    
    dataToShow.forEach(invitation => {
        const row = createInvitationRow(invitation);
        invitationTableBody.appendChild(row);
    });
    
    // 重新绑定事件
    bindCheckboxEvents();
}

// 创建邀请行
function createInvitationRow(invitation) {
    const row = document.createElement('tr');
    row.className = 'invitation-row';
    row.dataset.customerId = invitation.id;
    row.dataset.status = invitation.invitationStatus;
    
    const statusBadgeClass = getStatusBadgeClass(invitation.invitationStatus);
    const statusText = getStatusText(invitation.invitationStatus);
    const methodsHtml = invitation.invitationMethods.map(method => 
        `<span class="method-item ${getMethodClass(method)}">
            <i class="${getMethodIcon(method)}"></i>
            ${method}
        </span>`
    ).join('');
    
    const tagsHtml = invitation.customerTags.map(tag => 
        `<span class="tag ${getTagClass(tag)}">${tag}</span>`
    ).join('');
    
    row.innerHTML = `
        <td>
            <label class="checkbox-item">
                <input type="checkbox" class="customer-checkbox" value="${invitation.id}">
                <span class="checkmark"></span>
            </label>
        </td>
        <td class="customer-info">
            <div class="customer-detail">
                <div class="customer-avatar">${invitation.customerAvatar}</div>
                <div class="customer-data">
                    <div class="customer-name">${invitation.customerName}</div>
                    <div class="customer-phone">${invitation.customerPhone}</div>
                    <div class="customer-tags">${tagsHtml}</div>
                </div>
            </div>
        </td>
        <td class="invitation-method">
            <div class="method-list">${methodsHtml}</div>
        </td>
        <td class="invitation-time">
            <div class="time-info">
                <div class="first-time">首次：${formatDateTime(invitation.firstInviteTime)}</div>
                <div class="last-time">最近：${formatDateTime(invitation.lastInviteTime)}</div>
            </div>
        </td>
        <td class="customer-feedback">
            <div class="feedback-content ${invitation.customerFeedback ? '' : 'empty'}">
                ${invitation.customerFeedback || '暂无反馈'}
            </div>
        </td>
        <td class="invitation-status">
            <span class="status-badge ${statusBadgeClass}">${statusText}</span>
        </td>
        <td class="follow-up">
            <div class="follow-up-info ${invitation.invitationStatus === 'pending' ? 'urgent' : ''}">
                <div class="next-time">${invitation.followUpTime}</div>
                <div class="follow-method">${invitation.followUpMethod}</div>
            </div>
        </td>
        <td class="actions">
            <div class="action-buttons">
                ${getActionButtons(invitation)}
            </div>
        </td>
    `;
    
    return row;
}

// 获取操作按钮
function getActionButtons(invitation) {
    let buttons = `
        <button class="action-btn" title="查看详情" onclick="viewInvitationDetail(${invitation.id})">
            <i class="fas fa-eye"></i>
        </button>
    `;
    
    if (invitation.invitationStatus === 'pending') {
        buttons += `
            <button class="action-btn primary" title="立即跟进" onclick="followUpCustomer(${invitation.id})">
                <i class="fas fa-phone"></i>
            </button>
        `;
    } else if (invitation.invitationStatus === 'confirmed') {
        buttons += `
            <button class="action-btn" title="联系客户" onclick="contactCustomer(${invitation.id})">
                <i class="fas fa-phone"></i>
            </button>
        `;
    } else if (invitation.invitationStatus === 'rejected') {
        buttons += `
            <button class="action-btn" title="关怀客户" onclick="careCustomer(${invitation.id})">
                <i class="fas fa-heart"></i>
            </button>
        `;
    }
    
    buttons += `
        <button class="action-btn" title="更多操作" onclick="showInvitationActions(${invitation.id})">
            <i class="fas fa-ellipsis-h"></i>
        </button>
    `;
    
    return buttons;
}

// 绑定复选框事件
function bindCheckboxEvents() {
    const checkboxes = document.querySelectorAll('.customer-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', handleCustomerSelection);
    });
}

// 处理客户选择
function handleCustomerSelection() {
    const selectedCheckboxes = document.querySelectorAll('.customer-checkbox:checked');
    selectedCustomers = Array.from(selectedCheckboxes).map(cb => parseInt(cb.value));
    
    updateBatchActionsBar();
    updateSelectAllState();
}

// 处理全选
function handleSelectAll() {
    const checkboxes = document.querySelectorAll('.customer-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    
    handleCustomerSelection();
}

// 更新全选状态
function updateSelectAllState() {
    const allCheckboxes = document.querySelectorAll('.customer-checkbox');
    const checkedCheckboxes = document.querySelectorAll('.customer-checkbox:checked');
    
    if (checkedCheckboxes.length === 0) {
        selectAllCheckbox.indeterminate = false;
        selectAllCheckbox.checked = false;
    } else if (checkedCheckboxes.length === allCheckboxes.length) {
        selectAllCheckbox.indeterminate = false;
        selectAllCheckbox.checked = true;
    } else {
        selectAllCheckbox.indeterminate = true;
        selectAllCheckbox.checked = false;
    }
}

// 更新批量操作栏
function updateBatchActionsBar() {
    if (selectedCustomers.length > 0) {
        batchActionsBar.style.display = 'flex';
        selectedCountSpan.textContent = selectedCustomers.length;
    } else {
        batchActionsBar.style.display = 'none';
    }
}

// 切换视图
function switchView(view) {
    currentFilter = view;
    
    // 更新按钮状态
    viewBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.view === view);
    });
    
    // 重新渲染表格
    renderInvitationTable();
}

// 获取筛选后的数据
function getFilteredData() {
    let data = [...filteredData];
    
    // 按状态筛选
    if (currentFilter !== 'all') {
        data = data.filter(item => item.invitationStatus === currentFilter);
    }
    
    return data;
}

// 应用筛选条件
function applyFilters() {
    const customerStatus = getSelectedCheckboxValues('input[name="customer-status"]:checked');
    const selectedTags = Array.from(document.querySelectorAll('.tag-item.active')).map(item => item.dataset.tag);
    const ageMin = parseInt(document.getElementById('age-min').value);
    const ageMax = parseInt(document.getElementById('age-max').value);
    const region = document.getElementById('region-filter').value;
    const budget = document.getElementById('budget-filter').value;
    
    filteredData = invitationData.filter(item => {
        // 客户状态筛选
        if (customerStatus.length > 0 && !customerStatus.includes(item.customerStatus)) {
            return false;
        }
        
        // 标签筛选
        if (selectedTags.length > 0 && !selectedTags.some(tag => item.customerTags.includes(tag))) {
            return false;
        }
        
        // 年龄筛选
        if (item.age < ageMin || item.age > ageMax) {
            return false;
        }
        
        // 地域筛选
        if (region && item.region !== region) {
            return false;
        }
        
        // 预算筛选
        if (budget && item.budget !== budget) {
            return false;
        }
        
        return true;
    });
    
    renderInvitationTable();
    updateFilterResult();
    showNotification('筛选条件已应用', 'success');
}

// 重置筛选
function resetFilters() {
    // 重置复选框
    document.querySelectorAll('.checkbox-group input[type="checkbox"]').forEach(cb => {
        cb.checked = false;
    });
    
    // 重置标签选择
    document.querySelectorAll('.tag-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // 重置范围滑块
    document.getElementById('age-min').value = 55;
    document.getElementById('age-max').value = 75;
    document.getElementById('age-range-display').textContent = '55-75岁';
    
    // 重置下拉选择
    document.getElementById('region-filter').value = '';
    document.getElementById('budget-filter').value = '';
    
    // 重置数据
    filteredData = [...invitationData];
    renderInvitationTable();
    updateFilterResult();
    
    showNotification('筛选条件已重置', 'info');
}

// 更新筛选结果
function updateFilterResult() {
    const resultCount = document.querySelector('.result-count');
    const resultRecommend = document.querySelector('.result-recommend');
    
    if (resultCount) {
        resultCount.textContent = `${filteredData.length}个匹配客户`;
    }
    
    if (resultRecommend) {
        const recommendCount = Math.min(45, filteredData.length);
        resultRecommend.innerHTML = `推荐邀请：<strong>${recommendCount}人</strong>`;
    }
}

// 更新结果计数
function updateResultCount() {
    const counts = {
        all: invitationData.length,
        pending: invitationData.filter(item => item.invitationStatus === 'pending').length,
        confirmed: invitationData.filter(item => item.invitationStatus === 'confirmed').length,
        rejected: invitationData.filter(item => item.invitationStatus === 'rejected').length
    };
    
    viewBtns.forEach(btn => {
        const view = btn.dataset.view;
        const span = btn.querySelector('span');
        if (span && counts[view] !== undefined) {
            span.textContent = `${getViewText(view)} (${counts[view]})`;
        }
    });
}

// 更新统计数据
function updateStats() {
    const stats = {
        totalInvited: invitationData.length,
        confirmed: invitationData.filter(item => item.invitationStatus === 'confirmed').length,
        pending: invitationData.filter(item => item.invitationStatus === 'pending').length,
        rejected: invitationData.filter(item => item.invitationStatus === 'rejected').length
    };
    
    // 更新统计卡片
    const statCards = document.querySelectorAll('.stat-card');
    if (statCards[0]) {
        statCards[0].querySelector('.stat-number').textContent = stats.totalInvited;
    }
    if (statCards[1]) {
        statCards[1].querySelector('.stat-number').textContent = stats.confirmed;
        const confirmRate = ((stats.confirmed / stats.totalInvited) * 100).toFixed(1);
        statCards[1].querySelector('.stat-item').textContent = `确认率：${confirmRate}%`;
    }
    if (statCards[2]) {
        statCards[2].querySelector('.stat-number').textContent = stats.pending;
    }
    if (statCards[3]) {
        statCards[3].querySelector('.stat-number').textContent = stats.rejected;
        const rejectRate = ((stats.rejected / stats.totalInvited) * 100).toFixed(1);
        statCards[3].querySelector('.stat-item').textContent = `拒绝率：${rejectRate}%`;
    }
}

// 邀请相关函数
function viewInvitationDetail(customerId) {
    const invitation = invitationData.find(item => item.id === customerId);
    if (!invitation) return;
    
    // 构建详情内容
    const detailContent = document.getElementById('invitation-detail-content');
    detailContent.innerHTML = createInvitationDetailHTML(invitation);
    
    invitationDetailModal.classList.add('show');
}

function createInvitationDetailHTML(invitation) {
    return `
        <div class="detail-section">
            <h4>客户信息</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">姓名：</span>
                    <span class="detail-value">${invitation.customerName}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">电话：</span>
                    <span class="detail-value">${invitation.customerPhone}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">状态：</span>
                    <span class="detail-value">${invitation.customerStatus}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">年龄：</span>
                    <span class="detail-value">${invitation.age}岁</span>
                </div>
            </div>
        </div>
        
        <div class="detail-section">
            <h4>邀请记录</h4>
            <div class="detail-timeline">
                <div class="timeline-item">
                    <div class="timeline-time">${invitation.firstInviteTime}</div>
                    <div class="timeline-content">首次邀请 - ${invitation.invitationMethods[0]}</div>
                </div>
                ${invitation.lastInviteTime !== invitation.firstInviteTime ? `
                <div class="timeline-item">
                    <div class="timeline-time">${invitation.lastInviteTime}</div>
                    <div class="timeline-content">跟进邀请 - ${invitation.invitationMethods[invitation.invitationMethods.length - 1]}</div>
                </div>
                ` : ''}
            </div>
        </div>
        
        <div class="detail-section">
            <h4>客户反馈</h4>
            <div class="feedback-box">
                ${invitation.customerFeedback || '暂无反馈'}
            </div>
        </div>
    `;
}

function followUpCustomer(customerId) {
    showNotification('正在为您拨打客户电话...', 'info');
    // 这里实现跟进逻辑
}

function contactCustomer(customerId) {
    showNotification('正在为您拨打客户电话...', 'info');
    // 这里实现联系客户逻辑
}

function careCustomer(customerId) {
    showNotification('客户关怀功能正在开发中...', 'info');
    // 这里实现客户关怀逻辑
}

function showInvitationActions(customerId) {
    showNotification('更多操作功能正在开发中...', 'info');
    // 这里实现更多操作菜单
}

// 批量操作函数
function batchInvite() {
    if (selectedCustomers.length === 0) {
        showNotification('请先选择要邀请的客户', 'warning');
        return;
    }
    openInvitationModal();
}

function batchFollowUp() {
    if (selectedCustomers.length === 0) {
        showNotification('请先选择要跟进的客户', 'warning');
        return;
    }
    showNotification(`正在为${selectedCustomers.length}个客户安排跟进任务...`, 'info');
}

function batchExport() {
    if (selectedCustomers.length === 0) {
        showNotification('请先选择要导出的客户', 'warning');
        return;
    }
    showNotification('正在导出客户邀请数据...', 'info');
}

// 模态框函数
function openInvitationModal() {
    invitationModal.classList.add('show');
}

function closeInvitationModal() {
    invitationModal.classList.remove('show');
}

function closeInvitationDetailModal() {
    invitationDetailModal.classList.remove('show');
}

function confirmInvitation() {
    const selectedMethods = Array.from(document.querySelectorAll('.method-option input:checked')).map(input => input.value);
    const template = document.getElementById('invitation-template').value;
    const followupTime = document.getElementById('first-followup').value;
    const followupMethod = document.getElementById('followup-method').value;
    
    if (selectedMethods.length === 0) {
        showNotification('请选择至少一种邀请方式', 'warning');
        return;
    }
    
    showNotification(`正在通过${selectedMethods.length}种方式邀请${selectedCustomers.length || 1}个客户...`, 'success');
    closeInvitationModal();
    
    // 清除选择
    selectedCustomers = [];
    updateBatchActionsBar();
    selectAllCheckbox.checked = false;
    document.querySelectorAll('.customer-checkbox').forEach(cb => cb.checked = false);
}

function editInvitation() {
    showNotification('编辑邀请功能正在开发中...', 'info');
    closeInvitationDetailModal();
}

function addFollowUp() {
    showNotification('添加跟进功能正在开发中...', 'info');
    closeInvitationDetailModal();
}

// 工具函数
function getSelectedCheckboxValues(selector) {
    return Array.from(document.querySelectorAll(selector)).map(cb => cb.value);
}

function getStatusBadgeClass(status) {
    const classMap = {
        'confirmed': 'status-confirmed',
        'pending': 'status-pending',
        'rejected': 'status-rejected',
        'considering': 'status-considering'
    };
    return classMap[status] || 'status-pending';
}

function getStatusText(status) {
    const textMap = {
        'confirmed': '已确认',
        'pending': '待回复',
        'rejected': '已拒绝',
        'considering': '考虑中'
    };
    return textMap[status] || '未知';
}

function getViewText(view) {
    const textMap = {
        'all': '全部',
        'pending': '待回复',
        'confirmed': '已确认',
        'rejected': '已拒绝'
    };
    return textMap[view] || '未知';
}

function getMethodClass(method) {
    if (method.includes('电话')) return 'method-phone';
    if (method.includes('微信')) return 'method-wechat';
    if (method.includes('短信')) return 'method-sms';
    return 'method-other';
}

function getMethodIcon(method) {
    if (method.includes('电话')) return 'fas fa-phone';
    if (method.includes('微信')) return 'fab fa-weixin';
    if (method.includes('短信')) return 'fas fa-comment';
    return 'fas fa-envelope';
}

function getTagClass(tag) {
    const classMap = {
        'VIP客户': 'tag-vip',
        '身体健康': 'tag-health',
        '优质客户': 'tag-quality',
        '需要关怀': 'tag-careful',
        '普通客户': 'tag-normal'
    };
    return classMap[tag] || 'tag-normal';
}

function formatDateTime(dateTimeStr) {
    const date = new Date(dateTimeStr);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    return `${month}-${day} ${hour}:${minute}`;
}

function goBackToActivity() {
    window.location.href = 'invitation-management.html';
}

// 通用函数
function handleModalClick(event) {
    if (event.target.classList.contains('modal-overlay')) {
        closeInvitationModal();
        closeInvitationDetailModal();
    }
}

function handleKeyDown(event) {
    if (event.key === 'Escape') {
        closeInvitationModal();
        closeInvitationDetailModal();
    }
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${getNotificationIcon(type)}"></i>
        <span>${message}</span>
    `;
    
    document.body.appendChild(notification);
    
    notification.style.position = 'fixed';
    notification.style.top = '80px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.minWidth = '300px';
    notification.style.animation = 'slideInRight 0.3s ease-out';
    
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease-in';
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

function getNotificationIcon(type) {
    const iconMap = {
        'info': 'info-circle',
        'success': 'check-circle',
        'warning': 'exclamation-triangle',
        'error': 'times-circle'
    };
    return iconMap[type] || 'info-circle';
}

// 导出函数供HTML使用
window.viewInvitationDetail = viewInvitationDetail;
window.followUpCustomer = followUpCustomer;
window.contactCustomer = contactCustomer;
window.careCustomer = careCustomer;
window.showInvitationActions = showInvitationActions;
window.batchInvite = batchInvite;
window.batchFollowUp = batchFollowUp;
window.batchExport = batchExport;
window.openInvitationModal = openInvitationModal;
window.closeInvitationModal = closeInvitationModal;
window.closeInvitationDetailModal = closeInvitationDetailModal;
window.confirmInvitation = confirmInvitation;
window.editInvitation = editInvitation;
window.addFollowUp = addFollowUp;
window.goBackToActivity = goBackToActivity;